package com.woyao.core.model;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.woyao.core.model.BusinessCategory;

import java.io.IOException;
import java.util.ArrayList;

public class BusinessCategoryDeserializer extends JsonDeserializer<ArrayList<BusinessCategory>> {

    public BusinessCategoryDeserializer(){

    }
    @Override
    public ArrayList<BusinessCategory> deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode objectNode = jsonParser.readValueAsTree();

        if (null == objectNode                     // if no author node could be found
                || !objectNode.isArray()           // or author node is not an array
                || !objectNode.elements().hasNext())   // or author node doesn't contain any authors
            return null;
        ArrayNode node = (ArrayNode)objectNode;

        ArrayList<BusinessCategory> list = new ArrayList<>();
        for(JsonNode each : node){
            BusinessCategory category = new BusinessCategory();
            category.setNo(each.get("no").asText());
            category.setName(each.get("name").asText());
            category.setDescription(each.get("description").asText());
            category.setParentNo(each.get("top").asText());
            category.setImage(each.get("image").asText());
            category.setCount(each.get("value").asInt(0));
            list.add(category);
        }

        return list;
    }
}
